package severlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.TimeZone;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import dao.PassageMapper;
import model.Passage;
import util.SqlSessionUtil;


/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/WriterServlet")
/**
* @author 听风寂  ，林舒馨
* @date 2020/1/8
* @ClassName WriterServlet
*/
public class WriterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public WriterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		//获取JSON的数据
		
		TimeZone tz = TimeZone.getTimeZone("ETC/GMT-8");
		TimeZone.setDefault(tz);
		String author = request.getSession().getAttribute("user").toString();
		System.out.println(author);
		String title = request.getParameter("title");
		String body = request.getParameter("body");
		Passage newPassage = new Passage(author,title, body,new Date(),0);
		JSONObject object=new JSONObject();
		PrintWriter out = response.getWriter();  
		SqlSession s = SqlSessionUtil.getSqlSession();
		PassageMapper up = s.getMapper(PassageMapper.class);
		int flag=up.inPassage(newPassage);
		s.commit();
		if(flag==1) {
			object.put("code","1");
		}
		else{
			
			object.put("code","0");
			}
		String jsonStr = JSON.toJSONString(object);
		out.print(jsonStr);
		out.close();	
				
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}
